package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import topicDao.MySqlTopicDao;
import topicDao.TopicEntity;

public class Topic extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Topic() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		MySqlTopicDao td = new MySqlTopicDao();
		List<TopicEntity> topic = td.findAll();
		request.setAttribute("topic", topic);
		request.getRequestDispatcher("Topic.jsp").forward(request, response);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		Long tid = Long.parseLong(request.getParameter("tid"));
		String tname = request.getParameter("tname");
		MySqlTopicDao t = new MySqlTopicDao();
		TopicEntity tt = new TopicEntity(tid, tname);
		int a = t.update(tt);
		if (a > 0) {
			out.print("<script>alert('编辑主题成功！');location.replace('Topic');</script>");
			return;
		}
		out.print("<script>alert('编辑主题失败！');history.back();</script>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
